package com.lw.tcpdemo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author LW
 * @2020/9/13 21:48
 */
public class TcpServerDemo01 {

    /*
            这样写，假设有中文的话，超过‘字节数’的时候就乱码了！

            byte[] buffer = new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }
             */
    public static void main(String[] args) {
        //提升一下作用域--------------
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        //服务端得有一个地址
        try {
            serverSocket = new ServerSocket(9999);
            while (true){//持续打开服务
                //2.等待客户端连接过来
                socket = serverSocket.accept();
                //3.读取客户端的消息
                is = socket.getInputStream();
                //管道流
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len=is.read(buffer))!=-1){
                    baos.write(buffer,0,len);
                }
                //里面无论怎么乱都没事，
                //直到输出的时候其实已经写完了
                System.out.println(baos.toString());

            }




        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源

            //按顺序‘倒着’  关闭
            if (baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
